<?php
namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\GoodsCategoryInterface;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-16 14:32
 *
 * @Description:
 */
class GoodsCategoryRepository extends Repository implements GoodsCategoryInterface
{
    protected $rules = [
        'created' => [
            'name' => 'required|min:2|max:16|unique:goods_category,name'
        ],
        'updated' => [
            'name' => 'required|min:2|max:16|unique:goods_category'
        ]
    ];

    protected $messages = [
        'name.required' => "分类名不能为空",
        'name.min' => "分类名不能少于2个字",
        'name.max' => "分类名不能多于16个字",
        'name.unique' => "分类名不能重复"
    ];

    protected function modelName()
    {
        return 'App\Model\GoodsCategory';
    }

    public function detail($id)
    {
        if (env('DIRECT_SALE')) {
            return $this->findBy('category_id', $id);
        }

        return $this->findBy('id', $id);
    }

    public function created(array $data)
    {
        if (env('DIRECT_SALE')) {
            throw new ValidateException('没有权限操作');
        }
        $this->validate($data, 'created');

        $lastId = $this->save($data);
        $lastId && $this->update(['category_id' => $lastId], $lastId, 'id');

        return $lastId;
    }

    public function lists($limit, $page, $map = [])
    {
        $query = $this->searchMap($map);
        $total = $query->count();
        $list = $query->orderBy('id', 'desc')->simplePaginate($limit, ['*'], 'page', $page);

        return $this->simplePaginate('list', $list->items(), $total, ceil($total/$limit), $page);
    }

    public function updated($id, array $data)
    {
        if (env('DIRECT_SALE')) {
            throw new ValidateException('没有权限操作');
        }
        $this->validate($data, 'updated', ['name' => $id]);

        return $this->update($data, $id, 'id');
    }

    public function findIdForFirst()
    {
        return $this->model->orderBy('updated_at', 'desc')->limit(1)->get()->toArray();
    }
}